package com.doform.android.xianggucheng.retrofit.ApiSpecTransformer;

import com.doform.android.xianggucheng.bean.Goods;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-08-05.
 * GitHub：https://github.com/cxydxpx
 */

public class ApiSpecTransformerArticleDown<T> implements ObservableTransformer<Goods, T> {
    @Override
    public ObservableSource<T> apply(@NonNull Observable<Goods> upstream) {
        return upstream
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Function<Goods, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(@NonNull final Goods goods) throws Exception {
                        return Observable.create(new ObservableOnSubscribe<T>() {
                            @Override
                            public void subscribe(@NonNull ObservableEmitter<T> e) throws Exception {
                                Goods goods1 = new Goods();
                                List<Goods.ListBean> newDatas = new ArrayList<>();

                                List<Goods.ListBean> list = goods.getList();
                                for (int i = 0; i < list.size(); i++) {
                                    Goods.ListBean listBean = list.get(i);
                                    if ("1".equals(listBean.getState())) {
                                        newDatas.add(listBean);
                                    }
                                }
                                goods1.setList(newDatas);

                                e.onNext((T) goods1);
                                e.onComplete();

                            }
                        });
                    }
                });
    }
}
